package com.example.kotlincourse

import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.commonbiz.BaseVMActivity
import com.example.kotlincourse.databinding.ActivityListBinding
import com.example.kotlincourse.viewmodel.MainViewModel

class ListActivity : BaseVMActivity<MainViewModel, ActivityListBinding>() {

    private var items = emptyList<ItemEntity>()
    private val avatar = "https://iknow-pic.cdn.bcebos.com/a9d3fd1f4134970a87e2c9af87cad1c8a6865d99"
    private lateinit var adapter: ItemAdapter

    override fun getViewModelClass() = MainViewModel::class.java

    override fun inflateBinding(layoutInflater: LayoutInflater) =
        ActivityListBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initView()
        initData()
    }

    private fun initData() {

        items = listOf(
            ItemEntity(1, "张飞", "一员猛将", avatar),
            ItemEntity(2, "关羽", "一员猛将2", avatar),
            ItemEntity(3, "黄忠", "三国第一射手", avatar)
        )
        adapter.submitList(items)
    }

    private fun initView() {

        adapter = ItemAdapter {}
        adapter.setOnItemClickListener(object : ItemAdapter.OnItemClickListener {

            override fun onItemClick(item: ItemEntity) {
                Toast.makeText(baseContext, "click:" + item.title, Toast.LENGTH_SHORT).show()
            }

            override fun onDelItemClick(item: ItemEntity) {
                val newList = adapter.currentList.toMutableList().apply {
                    remove(item)
                }
                adapter.submitList(newList)
            }
        })

        binding.refreshLayout.setOnRefreshListener {
            initData()
            binding.refreshLayout.finishRefresh(1500)
        }

        binding.btnAdd.setOnClickListener {
            val newList = adapter.currentList.toMutableList().apply {
                add(ItemEntity(4, "吕布", "三国第一猛将", avatar))
            }
            adapter.submitList(newList)
        }

        binding.btnReset.setOnClickListener{
            initData()
        }

        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager = LinearLayoutManager(baseContext)
    }
}